#!/opt/semaphore/apps/ansible/11.1.0/venv/bin/python
import sys
import json
from requests_oauthlib import OAuth1Session
import os


# 自动查找 all.yaml 的路径（优先 group_vars，再 vars）

MAAS_URL = "http://10.10.23.252:5240/MAAS/"
API_KEY = "RcZXyROn61jcwOGbxQ:6NWzb9XDVG8Qq2p5Dt:zMBmHqAzVdrKJMpmN8h0uIHjbkk8wA02"

# 拆分 API KEY
client_key, token_key, token_secret = API_KEY.split(':')
session = OAuth1Session(
    client_key=client_key,
    resource_owner_key=token_key,
    resource_owner_secret=token_secret
)


def get_machines(zone):
    url = f"{MAAS_URL}api/2.0/machines/?zone={zone}"
    resp = session.get(url)
    resp.raise_for_status()
    return resp.json()


def get_os_mapping():
    return {
        "8": "centos8",
        "7": "centos7",
        "focal": "ubuntu20",
        "jammy": "ubuntu22",
        "noble": "ubuntu24",
        "": "none"
    }


def build_inventory(machines):
    os_mapping = get_os_mapping()
    inventory = {
        '_meta': {
            'hostvars': {}
        }
    }

    for machine in machines:
        if machine['status_name'] == 'Deployed':
            status = "deployed"
        else:
            status = "none"
        distro = machine.get('distro_series', '').lower()
        group_name = f"{machine.get('zone', {}).get('name', 'default')}"
        ansible_user = "root123"
        hostname = machine['hostname']
        fqdn = machine['fqdn']

        if group_name not in inventory:
            inventory[group_name] = {
                'hosts': []
            }
        if hostname not in inventory[group_name]["hosts"]:
            inventory[group_name]['hosts'].append(hostname)
            inventory['_meta']['hostvars'][hostname] = {
                'ansible_user': ansible_user,
                'status': status,
                'os': os_mapping[distro],
                'hostname': machine.get('hostname'),
                'ansible_ssh_host': fqdn
            }

    return inventory


def main():
    zone = "Product"
    if len(sys.argv) == 2 and sys.argv[1] == "--list":
        all_machines = get_machines(zone)
        inventory = build_inventory(all_machines)
        print(json.dumps(inventory, indent=2))
    else:
        print(json.dumps({}))


if __name__ == "__main__":
    main()
